package com.csyf.manager.controller.merchant;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.csyf.manager.entity.SysAgent;
import com.csyf.manager.entity.SysMerchant;
import com.csyf.manager.entity.SysPayment;
import com.csyf.manager.entity.SysUser;
import com.csyf.manager.service.PayMentBiz;
import com.csyf.manager.service.SysMerchBiz;
import com.csyf.manager.utils.page.JqGridVo;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @Author: casper
 * @Description: 商户代付Controller
 * @Date: Created in 2018/11/30 11:21
 */
@Controller
@RequestMapping("/merchPayment")
public class MerchPaymentController {

    @Autowired
    private PayMentBiz payMentService;

    @Autowired
    private SysMerchBiz sysMerchBiz;

    /**
     * 商户代付列表
     * @param vo
     * @param page
     * @param rows
     * @return
     */
    @ResponseBody
    @PostMapping(value = "list")
    public JqGridVo list(SysPayment vo, Integer page, Integer rows) {

        //获取登录的代理商信息
        SysUser sysUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
        SysMerchant agent = sysMerchBiz.queryAgentByUserId(sysUser.getUserId());
        vo.setMchId(agent.getMerchMerchantNo());

        return payMentService.queryOrderByUserId(vo, page, rows);
    }

    @ResponseBody
    @RequestMapping(value = "exportExcle")
    public void exportExcle(SysPayment vo, HttpServletResponse response) throws Exception {
        SysUser sysUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
        SysMerchant merchant = sysMerchBiz.queryAgentByUserId(sysUser.getUserId());

        JqGridVo jqGridVo = payMentService.queryOrderByUserId(vo, 1, 100000);
        List<?> rows1 = jqGridVo.getRows();

        ExportParams exportParams = new ExportParams("代付列表", "代付列表 ", ExcelType.XSSF);

        Workbook sheets = ExcelExportUtil.exportExcel(exportParams, SysPayment.class, rows1);

        ServletOutputStream outputStream = response.getOutputStream();

        response.setContentType("application/x-msdownload");
        response.setHeader("Content-Disposition", "attachment; filename="
                + URLEncoder.encode(merchant.getMerchMerchantNo() + "_" + new SimpleDateFormat("yyyyMMdd").format(new Date()) + ".xlsx", "UTF-8"));

        sheets.write(outputStream);


        sheets.close();

    }


}
